import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_application_cyber/pages/Home/cn_home_page.dart';
import 'package:flutter_application_cyber/pages/Mian/cn_tabaBar_page.dart';
import 'package:flutter_application_cyber/tools/cn_device_utils.dart';
import 'package:flutter_application_cyber/model/cn_net_response.dart';
import 'package:flutter_application_cyber/net/cn_net_helper.dart';
import 'package:flutter_application_cyber/net/cn_net_api.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_application_cyber/model/cn_user_default_cache.dart';
import 'package:flutter_application_cyber/tools/cn_app_webView.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import '../../tools/cn_click_utils.dart';
import 'package:provider/provider.dart';
import '../../model/cn_strategy_model.dart';
import 'package:flutter_application_cyber/model/cn_strategy_vmodel.dart';
import 'package:flutter_application_cyber/tools/cn_log_pv_manger.dart';

class CnLoginPage extends StatefulWidget {
  const CnLoginPage({Key? key}) : super(key: key);

  @override
  State<CnLoginPage> createState() => _CnLoginPageState();
}

class _CnLoginPageState extends State<CnLoginPage> {
  bool _selectedPrivacyAgreement = false;

  @override
  Widget build(BuildContext context) {
    return 
    WillPopScope(
      child: Scaffold(
        body: Container(
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage('images/icon_wecome_bg.png'), fit: BoxFit.fill),
      ),
      child: Column(
        children: [
          Container(
            margin: EdgeInsets.only(top: 360),
            width: double.infinity,
            child: Column(
              children: [
                Container(
                  width: 88,
                  height: 88,
                  child: Image.asset(
                    'images/app_logo.png',
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(top: 10),
                    width: 107,
                    height: 25,
                    child: Image.asset('images/icon_app_name.png'))
              ],
            ),
          ),
          InkWell(
            onTap: () {
              if (!CnClickUtils.isClick()) return;
              if (_selectedPrivacyAgreement == false) {
                _showCustomDialog(context, (String isSure) {
                  if (isSure == 'Agree') {
                    loginInFastLogin();
                  }
                });
                return;
              }
              loginInFastLogin();
            },
            child: Container(
              margin: EdgeInsets.only(top: 65),
              width: 252,
              height: 50,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('images/icon_fast_login.png'))),
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 43),
                  width: 24,
                  height: 24,
                  child: Image.asset('images/icon_fast_login_small.png'),
                ),
                Container(
                  margin: EdgeInsets.only(left: 20),
                  child: Text(
                    'Fast Login',
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                )
              ]),
            ),
          ),
          InkWell(
            onTap: () {
              if (!CnClickUtils.isClick()) return;

              if (_selectedPrivacyAgreement == false) {
                _showCustomDialog(context, (String isSure) {
                  if (isSure == 'Agree') {
                    loginInAppleLogin();
                  }
                });
                return;
              }
              loginInAppleLogin();
            },
            child: Container(
              margin: EdgeInsets.only(top: 20),
              width: 252,
              height: 50,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('images/icon_login_in_app.png'))),
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 43),
                  width: 24,
                  height: 24,
                  child: Image.asset('images/icon_apple_logo.png'),
                ),
                Container(
                  margin: EdgeInsets.only(left: 5),
                  child: Text(
                    'Sign in with Apple',
                    style: TextStyle(fontSize: 16, color: Color(0xFF1C0D15)),
                  ),
                )
              ]),
            ),
          ),
          Container(
            padding: const EdgeInsets.fromLTRB(30, 50, 30, 0),
            child: _getPrivacyPolicy(),
          ),
        ],
      ),
    )), 
      onWillPop: () async => false);
    
  }

  Widget _getPrivacyPolicy() {
    return SizedBox(
      width: 300,
      height: 60,
      child: Column(children: [
        Row(
          children: [
            SizedBox(
              height: 40.0,
              width: 40.0,
              child: IconButton(
                  icon: Image.asset(_selectedPrivacyAgreement
                      ? 'images/ic_a_selected.png'
                      : 'images/a_ic_unselected.png'),
                  onPressed: () {
                    print('login');
                    // ToastUtil.showToast('选择');
                    if (_selectedPrivacyAgreement == false) {
                      _selectedPrivacyAgreement = true;
                      setState(() {});
                    } else {
                      _selectedPrivacyAgreement = false;
                      setState(() {});
                    }
                  }),
            ),
            Text('By using our App you agree with our',
                style: TextStyle(color: Colors.white, fontSize: 14)),
          ],
        ),
        RichText(
          text: TextSpan(children: [
            TextSpan(
                text: ('Term of Use '),
                style: TextStyle(color: Color(0xFFEA248F), fontSize: 14),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    // 查看 服务协议
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const CnBaseWebView(
                                url: CnApiNet.kUserProtocolUrl,
                                title: 'Term of Use ',
                              )),
                    );
                  }),
            TextSpan(
              text: ('and'),
              style: TextStyle(color: Colors.white, fontSize: 14),
            ),
            TextSpan(
                text: (' Privacy Policy'),
                style: TextStyle(color: Color(0xFFEA248F), fontSize: 14),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    // 查看 隐私政策
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const CnBaseWebView(
                                url: CnApiNet.kPrivacyPolicyUrl,
                                title: 'Privacy Policy',
                              )),
                    );
                  }),
          ]),
        ),
      ]),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  Future<String> _getId() async {
    return await CnDeviceUtils.getDeviceId();
  }

  loginInFastLogin() {
    _getId().then((id) {
      EasyLoading.show();
      CnNetHelper.userLogin(id, 4,
          (HDHResponseData? resp, bool result, String msg) async {
        if (result) {
          CnLogPvManger.stat(
              page: 'quicklogin',
              subPage: 'subPage',
              terPage: 'terPage',
              broadcasterId: 'broadcasterId');
          CnLogPvManger.stat(
              page: 'loginsuccess',
              subPage: 'subPage',
              terPage: 'terPage',
              broadcasterId: 'broadcasterId');

          UserData userData = UserData.fromJson(resp?.data);
          CnUserDefaultCacheHelper.setUserDefault(
              'userId', userData.userInfo?.userId);
          CnUserDefaultCacheHelper.setUserDefault('token', userData.token);
          CnUserDefaultCacheHelper.setUserDefault(
              'country', userData.userInfo?.country);

          await Provider.of<CnStrategyViewModel>(context, listen: false)
              .questStrategyBlock();
          await CnNetHelper.getAppConfig();
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const CnTabaBarPage()),
          );
        }
        EasyLoading.dismiss();
      });
    });
  }

  loginInAppleLogin() {
    SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    ).then((credential) {
      EasyLoading.show(status: 'loading...');
      CnNetHelper.userLogin(credential.identityToken!, 3,
          (dynamic resp, bool result, String msg) async {
        if (result) {
          CnLogPvManger.stat(
              page: 'applelogin',
              subPage: 'subPage',
              terPage: 'terPage',
              broadcasterId: 'broadcasterId');
          CnLogPvManger.stat(
              page: 'loginsuccess',
              subPage: 'subPage',
              terPage: 'terPage',
              broadcasterId: 'broadcasterId');

          UserData userData = UserData.fromJson(resp?.data);
          CnUserDefaultCacheHelper.setUserDefault(
              'userId', userData.userInfo!.userId);
          CnUserDefaultCacheHelper.setUserDefault('token', userData.token);
          await Provider.of<CnStrategyViewModel>(context, listen: false)
              .questStrategyBlock();
          await CnNetHelper.getAppConfig();
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const CnTabaBarPage()),
          );
        }
        EasyLoading.dismiss();
      });
    }).catchError(
      (e) {},
    );
  }
}

//弹窗
typedef FunctionTest<String> = void Function(String isSure);
void _showCustomDialog(context, FunctionTest<String> backBlock) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: Color(0xFFDACED8),
        shape: RoundedRectangleBorder(
          // borderRadius: BorderRadius.circular(10.0), // 设置边框半径
          side: BorderSide(color: Color(0xCC50082F), width: 3.0), // 设置边框颜色和宽度
        ),
        contentPadding:
            const EdgeInsets.only(top: 0, left: 24, right: 24, bottom: 0),
        content: Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              const SizedBox(height: 32),
              Container(
                width: 88,
                height: 88,
                child: Image.asset(
                  'images/icon_logo.png',
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 16),
                child: Text(
                  'CyberNex',
                  style: TextStyle(
                      color: Colors.black,
                      fontSize: 20,
                      fontWeight: FontWeight.bold),
                ),
              ),
              const SizedBox(height: 16),
              const Text('By using our App you agree with our',
                  style: TextStyle(color: Colors.black, fontSize: 14)),
              RichText(
                text: TextSpan(children: [
                  TextSpan(
                      text: ('Term of Use '),
                      style: TextStyle(color: Color(0xFFEA248F), fontSize: 14),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          CnLogPvManger.stat(
                              page: 'terms',
                              subPage: 'subPage',
                              terPage: 'terPage',
                              broadcasterId: 'broadcasterId');

                          // 查看 服务协议
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const CnBaseWebView(
                                      url: CnApiNet.kUserProtocolUrl,
                                      title: 'terms',
                                    )),
                          );
                        }),
                  TextSpan(
                    text: ('and'),
                    style: TextStyle(color: Colors.black, fontSize: 14),
                  ),
                  TextSpan(
                      text: (' Privacy Policy'),
                      style: TextStyle(color: Color(0xFFEA248F), fontSize: 14),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          CnLogPvManger.stat(
                              page: 'privacy',
                              subPage: 'subPage',
                              terPage: 'terPage',
                              broadcasterId: 'broadcasterId');

                          // 查看 隐私政策
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const CnBaseWebView(
                                      url: CnApiNet.kPrivacyPolicyUrl,
                                      title: 'Privacy Policy',
                                    )),
                          );
                        }),
                ]),
              ),
              InkWell(
                onTap: () {
                  backBlock('Agree');
                  Navigator.of(context).pop();
                },
                child: Container(
                    margin: EdgeInsets.only(top: 22),
                    width: 252,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('images/icon_fast_login.png'))),
                    child: Container(
                      child: Text(
                        'Agree and Continue',
                        style: TextStyle(fontSize: 16, color: Colors.white),
                      ),
                    )),
              ),
              InkWell(
                onTap: () {
                  backBlock('cancel');
                  Navigator.of(context).pop();
                },
                child: Container(
                    margin: EdgeInsets.only(top: 20),
                    width: 252,
                    height: 50,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('images/icon_btn_bg.png'))),
                    child: Container(
                      // margin: EdgeInsets.only(left: 5),
                      child: Text(
                        'Cancel',
                        style:
                            TextStyle(fontSize: 16, color: Color(0xFFA9A9A9)),
                      ),
                    )),
              ),
              const SizedBox(height: 30),
            ],
          ),
        ),
      );
    },
  );
}
